package hwr.iamdr.Service;

import java.io.IOException;

import java.util.logging.*;

import javax.servlet.http.*;
import javax.servlet.ServletException;

import com.google.appengine.api.datastore.*;

@SuppressWarnings("serial")
public class MainServlet extends HttpServlet
{
	static final DatastoreService dataStore	= DatastoreServiceFactory.getDatastoreService();
	static final Logger logger	= Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

	public static Entity UserSession(HttpServletRequest req)
	{
		String encodedKey	= (String)req.getSession().getAttribute("UserLogin");
		if(encodedKey != null && encodedKey.length() > 0)
		{
			try
			{
				return dataStore.get(KeyFactory.stringToKey(encodedKey));
			}
			catch(Exception e)
			{
				logger.log(Level.SEVERE,"Wrong Key : " + encodedKey + ",Don't Hack");
				req.getSession().removeAttribute("UserLogin");
			}
		}

		return null;
	}

	@Override
	protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
	{
		Entity entity	= UserSession(req);
		if(entity != null && entity.getProperty("Name") != null)
			getServletContext().getRequestDispatcher("/mainprofilepage.html").forward(req,resp);
		else getServletContext().getRequestDispatcher("/MainPage.html").forward(req,resp);
	}
}
